<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="证书编号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入证书编号"
          clearable
        />
      </el-form-item>
      <el-form-item label="证书名称" prop="name	">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入证书名称"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery" v-hasPermi="['portal:personnel-certificate:query']"
          >搜索</el-button
        >
        <!-- <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button> -->
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd" v-hasPermi="['portal:personnel-certificate:create']"
          >录入</el-button
        >
        <!-- <el-button
            type="primary"
            icon="el-icon-download"
            @click="handleExport"
            :loading="exportLoading"
            >导出</el-button
          > -->
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="certificateList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" type="index" width="55" align="center" />
      <el-table-column
        label="证书编号"
        align="center"
        prop="number"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="证书名称" align="center" prop="name" />
      <el-table-column label="证书描述" align="center" prop="description" />
      <el-table-column label="持证人" align="center" prop="personnelName">
        <template slot-scope="scope">
          <span>{{ scope.row.personnelName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="证书等级" align="center" prop="level">
        <template slot-scope="scope">
          <dict-tag :type="grade" :value="scope.row.level" />
        </template>
      </el-table-column>
      <el-table-column label="证书图片" align="center" prop="imageUrl">
        <template slot-scope="scope">
          <img
            :src="scope.row.imageUrl"
            alt=""
            width="100"
            height="60"
            style="cursor: pointer"
            @click="handlePictureCardPreview(scope.row.imageUrl)"
          />
        </template>
      </el-table-column>
      <el-table-column label="发放日期" align="center" prop="issueDate" />
      <el-table-column label="证书截止日期" align="center" prop="validUntil" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :type="CertificateStatus" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="240"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-view"
            v-hasPermi="['portal:personnel-certificate:update']"
            @click="handleChange(scope.row)"
            >变更</el-button
          >
          <el-button
            type="text"
            icon="el-icon-edit"
            v-hasPermi="['portal:personnel-certificate:update']"
            @click="handleUpdate(scope.row)"
            >更换</el-button
          >
          <!-- <el-button
              type="text"
              icon="el-icon-delete"
              @click="handleWithdraw(scope.row,'3')"
              >注销</el-button
            > -->
          <el-button
            type="text"
            icon="el-icon-delete"
            v-hasPermi="['portal:personnel-certificate:delete']"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        inline
        class="changeFrom"
      >
        <el-form-item label="证书名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入证书名称" />
        </el-form-item>
        <el-form-item label="证书等级" prop="level">
          <el-select
            v-model="form.level"
            placeholder="请选择证书等级"
            clearable
          >
            <el-option
              v-for="dict in getDictDatas('personnel_certificate_grade')"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="证书编号" prop="number">
          <el-input v-model="form.number" placeholder="请输入证书编号" />
        </el-form-item>
        <el-form-item label="持证人" prop="personnelId">
          <el-select
            v-model="form.personnelId"
            placeholder="请选择持证人"
            filterable
            clearable
          >
            <el-option
              v-for="personnel in personnelList"
              :key="personnel.id"
              :label="personnel.name"
              :value="personnel.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发放日期" prop="issueDate">
          <el-date-picker
            v-model="form.issueDate"
            type="date"
            placeholder="请选择发放日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="截止日期" prop="validUntil">
          <el-date-picker
            v-model="form.validUntil"
            type="date"
            placeholder="请选择截止日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="证书描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入证书描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="form.status"
            placeholder="请选择证书状态"
            clearable
          >
            <el-option
              v-for="certificate in getDictDatas(
                'personnel_certificate_status'
              )"
              :key="certificate.value"
              :label="certificate.label"
              :value="certificate.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="证书图片" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            :headers="imgUpload.headers"
            :action="imgUpload.url"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="form.imageUrl"
              width="192"
              height="108"
              :src="form.imageUrl"
              class="avatar1"
            />
            <el-button type="primary" v-else
              ><i class="el-icon-plus" size="mini">点击上传</i></el-button
            >
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" style="text-align: center">
      <img width="80%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <el-dialog title="证书状态变更" :visible.sync="changeOpen" width="500px">
      <el-form
        ref="form"
        :model="changeParams"
        :rules="rules"
        label-width="80px"
        inline
      >
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="changeParams.status"
            placeholder="请选择证书状态"
            clearable
          >
            <el-option
              v-for="certificate in getDictDatas(
                'personnel_certificate_status'
              )"
              :key="certificate.value"
              :label="certificate.label"
              :value="certificate.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="changeSubmitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCertificateList,
  createCertificate,
  updateCertificate,
  detailsCertificate,
  delCertificate,
  exportCertificate,
  changeStatus,
} from "@/api/personnel/certificate";
import { getPersonnelList } from "@/api/personnel/talent";
import { getAccessToken } from "@/utils/auth";
export default {
  name: "Notice",
  data() {
    return {
      dialogVisible: false,
      // 临时封面图片
      dialogImageUrl: null,
      //资质证书等级
      grade: "personnel_certificate_grade",
      //人员证书状态
      CertificateStatus: "personnel_certificate_status",
      // 遮罩层
      loading: true,
      //导出遮罩
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公告表格数据
      certificateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      changeOpen: false,
      // 证书上传参数
      imgUpload: {
        open: false, // 是否显示弹出层
        title: "", // 弹出层标题
        isUploading: false, // 是否禁用上传
        url: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload", // 请求地址
        headers: { Authorization: "Bearer " + getAccessToken() }, // 设置上传的请求头部
        data: {}, // 上传的额外数据，用于文件名
      },
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        personnelId: undefined,
        number: undefined,
        name: undefined,
      },
      changeParams: {
        id: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "证书名称不能为空", trigger: "blur" },
        ],
        level: [
          { required: true, message: "证书等级不能为空", trigger: "change" },
        ],
        issueDate: [
          { required: true, message: "证书描述不能为空", trigger: "change" },
        ],
        validUntil: [
          { required: true, message: "证书描述不能为空", trigger: "change" },
        ],
        personnelId: [
          { required: true, message: "人员编号不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "证书编号不能为空", trigger: "change" },
        ],
        number: [
          { required: true, message: "证书编号不能为空", trigger: "blur" },
        ],
        level: [
          { required: true, message: "证书编号不能为空", trigger: "change" },
        ],
        imageUrl: [
          { required: true, message: "证书编号不能为空", trigger: "change" },
        ],
      },
      personnelList: [],
    };
  },
  created() {
    if (this.$route.params.id) {
      this.queryParams.personnelId = this.$route.params.id;
      this.getList();
    }
    this.getPersonnelList();
  },
  methods: {
    /** 查询证书列表 */
    getList() {
      this.loading = true;
      getCertificateList(this.queryParams).then((response) => {
        this.certificateList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    getPersonnelList() {
      getPersonnelList(this.queryParams).then((res) => {
        this.personnelList = res.data.list;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        personnelId: undefined,
        number: undefined,
        description: undefined,
        imageUrl: undefined,
        level: undefined,
        issueDate: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      console.log(this.queryParams);
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.noticeId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 处理封面图片上传成功
    handleAvatarSuccess(file) {
      if (file.code == 0) {
        this.form.imageUrl = file.data;
      }
    },
    handleRemove(file) {
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    // 上传前检查图片格式
    beforeAvatarUpload(file) {
      const isJPGorPNG =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGorPNG) {
        this.$message.error("上传图片只能是 JPG 或 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPGorPNG && isLt2M;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "证书添加";
    },
    handleChange(row) {
      this.changeParams.id = row.id;
      this.changeOpen = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      detailsCertificate(row.id).then((response) => {
        this.form = response.data;
        this.form.status = String(this.form.status);
        this.open = true;
        this.title = "证书修改";
      });
    },
    changeSubmitForm() {
      changeStatus(this.changeParams).then((response) => {
        this.changeOpen = false;
        this.$modal.msgSuccess("变更成功");
        this.getList();
      });
    },
    /** 注销按钮操作 */
    // handleWithdraw(row,num){
    //   this.form.status = num;
    //   this.$modal
    //     .confirm('是否确认注销名字为"' + row.name + '"的证书为？').then(function () {
    //       return this.submitForm();
    //     })
    //     .then(() => {
    //       this.getList();
    //       this.$modal.msgSuccess("注销成功");
    //     })
    //     .catch(() => {});changeStatus
    // },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (this.form.issueDate) {
          this.form.issueDate = this.$moment(this.form.issueDate).format(
            "YYYY-MM-DD"
          );
        }
        if (this.form.validUntil) {
          this.form.validUntil = this.$moment(this.form.validUntil).format(
            "YYYY-MM-DD"
          );
        }
        if (valid) {
          if (this.form.id != undefined) {
            updateCertificate(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            createCertificate(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除证书编号为"' + row.name + '"的数据项？')
        .then(function () {
          return delCertificate(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$modal
        .confirm("是否确认导出证书数据项?")
        .then(() => {
          // 处理查询参数
          let params = { ...this.queryParams };
          params.pageNo = undefined;
          params.pageSize = undefined;
          this.exportLoading = true;
          return exportCertificate(params);
        })
        .then((response) => {
          this.$download.excel(response, "证书列表.xls");
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .talentFrom .el-input__inner {
  width: 220px !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 100px;
  border: 1px solid #9b9b9b;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}
.avatar {
  width: 178px;
  display: block;
  cursor: pointer;
}
.avatar1 {
  cursor: pointer;
}
</style>
